package se.webbzon.oschi01.nbt;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.NoSuchAlgorithmException;

import se.webbzon.oschi01.gzip.GZIPOutputStream;
import se.webbzon.oschi01.singleton.Singletons;
import se.webbzon.oschi01.utils.Writer;

import com.googlecode.asmack.connection.impl.ZLibOutputStream;

public class NBTOutputStreamWriter implements Writer<Tag<?>,OutputStream> {
	
	private final NBTCompression compression;

	public NBTOutputStreamWriter() {
		this(NBTCompression.NONE);
	}
	
	public NBTOutputStreamWriter(NBTCompression compression) {
		this.compression = compression;
	}
	
	@Override public void write(Tag<?> data, OutputStream destination) throws IOException {
		NBTDataOutputStreamWriter writer = Singletons.instance(NBTDataOutputStreamWriter.class);
		DataOutputStream dos = createDataOutputStream(destination);
		writer.write(data, dos);
		dos.flush();
	}
	
	private DataOutputStream createDataOutputStream(OutputStream os) throws IOException {
		switch (compression) {
		case ZLIB:
			try {
				return new DataOutputStream(new ZLibOutputStream(os));
			} catch (NoSuchAlgorithmException e) {
				throw new IOException(e);
			}
		case GZIP:
			return new DataOutputStream(new GZIPOutputStream(os));
		default:
			return new DataOutputStream(os);
		}
	}
	
}
